<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Taro from '@tarojs/taro';
import { Search2, Del2 } from '@nutui/icons-vue-taro';
import { clearSearchRecord, listSearchRecord, saveSearchRecord } from '@/service/api/search';

const searchValue = ref<string>('');
const recordList = ref<string[]>([]);

onMounted(() => {
  listSearchRecord().then((res: Service.SuccessResult) => {
    recordList.value = [...res.success];
  });
});

const onClear = () => {
  clearSearchRecord().then(() => (recordList.value = []));
};

const doSearchAndBack = () => {
  const pages = Taro.getCurrentPages();
  const current = pages[pages.length - 1];
  current.getOpenerEventChannel().emit('searchConfirm', { searchValue: searchValue.value });
  Taro.navigateBack({
    delta: 1
  });
};

const onSearch = () => {
  saveSearchRecord({ searchValue: searchValue.value });
  doSearchAndBack();
};

const onRecordClick = (row: string) => {
  searchValue.value = row;
  doSearchAndBack();
};
</script>

<template>
  <basic-layout :show-tab-bar="false">
    <custom-nav-bar title="搜索送礼人" left-show />
    <div class="w-375px text-30px text-primary">
      <nut-searchbar
        v-model="searchValue"
        confirm-type="search"
        autofocus
        :background="'#fff'"
        :input-background="'#fafafa'"
        style="margin-top: -1px"
      >
        <template #leftin>
          <Search2 />
        </template>
        <template #rightout>
          <div @click="onSearch">搜索</div>
        </template>
      </nut-searchbar>
      <div class="search-record">
        <nut-cell class="record-cell">
          <template #title>
            <span class="record-title">最近搜索</span>
          </template>
          <template #link>
            <Del2 @click="onClear" />
          </template>
        </nut-cell>
        <nut-tag
          v-for="(item, index) in recordList"
          :key="index"
          class="ml-20px text-2xl"
          color="#E9E9E9"
          text-color="#999999"
          plain
          round
          @click="onRecordClick(item)"
        >
          {{ item }}
        </nut-tag>
      </div>
    </div>
  </basic-layout>
</template>

<style lang="scss">
.search-record {
  width: 100%;
  min-height: 200px;

  .record-cell {
    background-color: #fafafa;
    margin-top: 10px;
    margin-bottom: 0;
    box-shadow: none;
    border-radius: 0;
    font-size: 14px;

    .record-title {
      color: #595757;
    }
  }

  /*.record-tag {
    margin-left: 20px;
    font-size: 12px;
  }*/
}
</style>
